/***************************************************************************
 *   Copyright (C) 2007 by Phillip Aldridge   *
 *   phillip@imi21.com    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "ftp.h"

#include "config.h"
#include <kled.h>
#include <qprogressbar.h>
#include <qftp.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qfiledialog.h>
#include <qprogressdialog.h>
#include <qapplication.h>

FTP::FTP(QWidget* parent):QWidget( parent,"UploadFTP" )
{
ftpFile="";

ftp = new QFtp( this );
qDebug( "FTP created" );
    connect( ftp, SIGNAL(commandStarted(int)),
            SLOT(ftp_commandStarted()) );
    connect( ftp, SIGNAL(commandFinished(int,bool)),
            SLOT(ftp_commandFinished(int,bool)) );
    connect( ftp, SIGNAL(done(bool)),
            SLOT(ftp_done(bool)) );
    connect( ftp, SIGNAL(stateChanged(int)),
            SLOT(ftp_stateChanged(int)) );
    connect( ftp, SIGNAL(listInfo(const QUrlInfo &)),
            SLOT(ftp_listInfo(const QUrlInfo &)) );
    connect( ftp, SIGNAL(rawCommandReply(int, const QString &)),
            SLOT(ftp_rawCommandReply(int, const QString &)) );
}


FTP::~FTP()
{
}

void FTP::destroy()
{
    if ( ftp->state() != QFtp::Unconnected )
        ftp->close();
}

void FTP::setHost(QString h,QString p)
{
   host=h;
   port=p;
}
void FTP:: setUser(QString u,QString p)
{
   user=u;
   password=p;
}
/**
   set the file name which should be uploaded
*/

void FTP::clearList()
{
   fileList.clear();
}
void FTP::addFile( QString s)
{
   fileList.append(s);
}

void FTP::connectToHost()
{

if (fileList.isEmpty()) return; // nothing to do

qDebug ("Connecting FTP");
    if ( ftp->state() != QFtp::Unconnected )
        ftp->close();

    ftp->connectToHost(QString( _FTP_HOST ),_FTP_PORT );
    ftp->login( QString( _FTP_USERNAME ), QString( _FTP_PASSWORD ) );
    ftp->rawCommand( "PWD" );
    ftp->cd( QString ( _FTP_DIRECTORY) );
    ftp->rawCommand( "PWD" );
    //ftp->list();
   uploadFile();

}

void FTP::uploadFile()
{
    QProgressDialog progress(
            tr("Uploading files..."),
            tr("Cancel"),
            0,
            this,
            "upload progress dialog",
            TRUE );
    connect( ftp, SIGNAL(dataTransferProgress(int,int)),
            &progress, SLOT(setProgress(int,int)) );
    connect( ftp, SIGNAL(done(bool)), //commandFinished(int,bool)),
            &progress, SLOT(reset()) );
    connect( &progress, SIGNAL(cancelled()),
            ftp, SLOT(abort()) );

/******************/
   QStringList::Iterator i = fileList.begin();
   while ( i != fileList.end() ){
   ftpFile=*i;
   qDebug("Uploading file :"+ftpFile) ;

    QFile *file = new QFile (ftpFile);
    if (file->open (IO_ReadOnly) == true) {
      QFileInfo fi( ftpFile );
      ftp->put( file, fi.fileName() );
    }
   i++;
  }
  ftp->close();

   progress.exec(); //takes a lot of time!!!

}



/****************************************************************************
**
** Slots connected to signals of the QFtp class
**
*****************************************************************************/

void FTP::ftp_commandStarted()
{
   // if ( ftp->currentCommand() == QFtp::List ) {
        //remoteView->clear();
       // if ( currentFtpDir != "/" )
//            new FtpViewItem( remoteView, FtpViewItem::Directory, "..", "", "" );
    //}

}

void FTP::ftp_commandFinished(int id, bool error)
{
qDebug ("ftp_commandFinished %i",id);
if (error) qDebug(ftp->errorString ());
   delete ftp->currentDevice();
}

void FTP::ftp_done( bool error )
{
qDebug ("ftp_done");
    if ( error ) {
        QMessageBox::critical( this, tr("FTP Error"), ftp->errorString() );

        // If we are connected, but not logged in, it is not meaningful to stay
        // connected to the server since the error is a really fatal one (login
        // failed).
        if ( ftp->state() == QFtp::Connected )
            ftp->close();
    }
}

void FTP::ftp_stateChanged( int state )
{

    switch ( (QFtp::State)state ) {
        case QFtp::Unconnected:
            qDebug( "Unconnected" );
            break;
        case QFtp::HostLookup:
            qDebug( "Host lookup" );
            break;
        case QFtp::Connecting:
            qDebug( "Connecting" );
            break;
        case QFtp::Connected:
            qDebug( "Connected" );
            break;
        case QFtp::LoggedIn:
            qDebug( "Logged in" );
            break;
        case QFtp::Closing:
            qDebug( "Closing" );
            break;
    }
}



void FTP::ftp_rawCommandReply( int code, const QString &text )
{
qDebug("FTP raw : "+text);
    if ( code == 257 ) {
       // currentFtpDir = text.section( '"', 1, 1 );

        //for ( int i = 0; i<remotePath->count(); i++ ) {
            // make sure that we don't insert duplicates
           // if ( remotePath->text( i ) == currentFtpDir )
            //    remotePath->removeItem( i );
        //}
        //remotePath->insertItem( currentFtpDir, 0 );
       // remotePath->setCurrentItem( 0 );
    }
}

void FTP::ftp_listInfo( const QUrlInfo &url)
{
qDebug(url.name ());
}


